package com.sunshine.lnuplus.adapter

import android.app.Activity
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.LinearLayout
import androidx.cardview.widget.CardView
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.textfield.TextInputLayout
import com.sunshine.lnuplus.R
import com.sunshine.lnuplus.model.room.CountDown
import com.sunshine.lnuplus.model.room.TimetableRepository
import com.sunshine.lnuplus.utils.ColorUtils
import com.sunshine.lnuplus.utils.DateUtils
import com.sunshine.lnuplus.view.DialogWithView
import com.sunshine.lnuplus.view.DialogWithoutView
import com.sunshine.lnuplus.view.ScrollTextView
import es.dmoral.toasty.Toasty
import java.text.DecimalFormat

class CountDownRecyclerAdapter(
    private val context: Context,
    private val countDownList: ArrayList<CountDown?>?,
    private val fm: FragmentManager,
    private val repository: TimetableRepository
) : RecyclerView.Adapter<CountDownRecyclerAdapter.RecyclerViewHolder>() {

    class RecyclerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val lessonName: ScrollTextView = itemView.findViewById(R.id.countdown_lessonName)
        val location: ScrollTextView = itemView.findViewById(R.id.countdown_location)
        val time: ScrollTextView = itemView.findViewById(R.id.countdown_time)
        val countDown: ScrollTextView = itemView.findViewById(R.id.countdown_count_down)
        val cardView: CardView = itemView.findViewById(R.id.item_count_down_card_view)

        init {
            val linearLayout: LinearLayout = itemView.findViewById(R.id.item_count_down_linear)
            val width: Int = (linearLayout.context as Activity).windowManager.defaultDisplay.width
            val params = linearLayout.layoutParams
            params.width = width / 2
            params.height = (400 + Math.random() * 100).toInt()
            linearLayout.layoutParams = params
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerViewHolder {
        return RecyclerViewHolder(
            LayoutInflater.from(context).inflate(
                R.layout.item_count_down_recycler_view,
                parent,
                false
            )
        )
    }

    override fun getItemCount(): Int {
        return if (countDownList.isNullOrEmpty()) 0 else countDownList.size
    }

    override fun onBindViewHolder(holder: RecyclerViewHolder, position: Int) {
        val countDownDate = DateUtils.getCountDownTime(countDownList?.get(position)!!.time)
        val colorUtils = ColorUtils
        colorUtils.init(context)

        if(countDownDate < 0){
            holder.cardView.setCardBackgroundColor(Color.GRAY)
        }else{
            holder.cardView.setCardBackgroundColor(
                if (countDownList.get(position)!!.color == "0") colorUtils.setBackgroundColor(countDownList[position]!!.lessonName) else Color.parseColor(countDownList[position]!!.color)
            )
        }
        holder.lessonName.text = countDownList[position]!!.lessonName
        holder.location.text =
            if (countDownList[position]!!.location.isEmpty()) "点击填写地点" else countDownList[position]!!.location
        holder.time.text =
            if (countDownList[position]!!.time.isEmpty()) "点击选择时间" else countDownList[position]!!.time
        if (countDownDate < 0){
            holder.countDown.text =
                if (countDownList[position]!!.time.isEmpty()) "" else "已过${-DateUtils.getCountDownTime(countDownList[position]!!.time)}天"
        }else{
            holder.countDown.text =
                if (countDownList[position]!!.time.isEmpty()) "" else "距离开始还有${DateUtils.getCountDownTime(countDownList[position]!!.time)}天"
        }

        holder.cardView.setOnLongClickListener {
            val positive = DialogInterface.OnClickListener { _, _ ->
                repository.deleteCountDown(holder.lessonName.text.toString())
                Toasty.success(context,"删除成功~",Toasty.LENGTH_SHORT).show()
            }
            DialogWithoutView.newInstance("提醒","你真的要删除这个倒计时吗",false, positive, null).show(fm, "delete_countdown")
            true
        }
        holder.lessonName.setOnClickListener{
            val view = LayoutInflater.from(context)
                .inflate(R.layout.dialog_edit_count_down_location, null, false)
            val edit = view.findViewById<androidx.appcompat.widget.AppCompatEditText>(R.id.edit_count_down_location)
            val til_edit = view.findViewById<TextInputLayout>(R.id.til_count_down_location)
            til_edit.counterMaxLength = 30
            edit.setText(holder.lessonName.text.toString())
            edit.hint = "请输入名称"
            val dialog = DialogWithView.newInstance(
                view,
                "请填写名称",
                true,
                DialogInterface.OnClickListener { _, _ ->
                    when {
                        edit.text!!.isEmpty() -> {
                            Toasty.success(context, "名称不能为空~", Toasty.LENGTH_SHORT).show()
                        }
                        edit.text!!.length > 30 -> {
                            Toasty.success(context, "名称太长了，我记不住~", Toasty.LENGTH_SHORT).show()
                        }
                        else -> {
                            repository.updateCountDownName(
                                countDownList[position]!!.lessonName,
                                edit.text.toString()
                            )
                            Toasty.success(context, "保存成功", Toasty.LENGTH_SHORT).show()
                        }
                    }
                },
                null)
            dialog.show(fm, "editLocation")
        }
        holder.location.setOnClickListener {
            val view = LayoutInflater.from(context)
                .inflate(R.layout.dialog_edit_count_down_location, null, false)
            val edit = view.findViewById<androidx.appcompat.widget.AppCompatEditText>(R.id.edit_count_down_location)
            val til_edit = view.findViewById<TextInputLayout>(R.id.til_count_down_location)
            edit.hint = "请输入地点"
            val dialog = DialogWithView.newInstance(
                view,
                "请填写地点",
                true,
                DialogInterface.OnClickListener { _, _ ->
                    when {
                        edit.text!!.isEmpty() -> {
                            Toasty.success(context, "地点不能为空~", Toasty.LENGTH_SHORT).show()
                        }
                        edit.text!!.length > 15 -> {
                            Toasty.success(context, "地点太长了，我记不住~", Toasty.LENGTH_SHORT).show()
                        }
                        else -> {
                            repository.updateCountDownLocation(
                                countDownList[position]!!.lessonName,
                                edit.text.toString()
                            )
                            Toasty.success(context, "保存成功", Toasty.LENGTH_SHORT).show()
                        }
                    }
                },
                null)
            dialog.show(fm, "editLocation")
        }
        holder.time.setOnClickListener {
            val datePickerDialog = DatePickerDialog(context,
                DatePickerDialog.OnDateSetListener { _, year, month, dayOfMonth ->
                    val timePickerDialog = TimePickerDialog(
                        context,
                        TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute ->
                            val time =
                                year.toString() + "-" + (month + 1) + "-" + dayOfMonth + " " + hourOfDay + ":" + DecimalFormat(
                                    "00"
                                ).format(minute.toLong()) //格式化
                            repository.updateCountDownTime(countDownList[position]!!.lessonName, time, year, month, dayOfMonth, hourOfDay, minute)
                            notifyDataSetChanged()
                            Toasty.success(context, "保存成功", Toasty.LENGTH_SHORT).show()
                        },
                        DateUtils.hour,
                        DateUtils.minute,
                        true
                    )
                    timePickerDialog.show()
                }, DateUtils.year, DateUtils.month - 1, DateUtils.day
            )
            datePickerDialog.show()
        }
    }
}